<?PHP
class Resource {
	
	public $path;

	public $folder;

	public $file;

	public $errors = false;
	
	public static function create_from_request() {

		$path = $_GET[TeeWee::$CONFIG->GET_PAGE];
		// Check for file inclusion attacks
		if(preg_match('/\.\./',$path))
			TeeWee::$TEEWEE->redirect_intern(TeeWee::$CONFIG->PAGE_ERRORS.'/403');

		// See if the request is a service
		elseif(preg_match('/^'.TeeWee::$CONFIG->SERVICE_PREFIX.'\//',$path)) {
			$resource = new Service(substr($path, 2));
		}

		// Otherwise it's a plain page request
		else
			$resource = new Page($path); 

		if(! file_exists($resource->path))
			TeeWee::$TEEWEE->redirect_intern(TeeWee::$CONFIG->PAGE_ERRORS.'/404',array());

		return $resource;
	}

	public function __construct($folder,$file) {
		$this->folder = 'resources'.'/'.$folder;
		$this->path = $this->folder.'/'.$file;
		$this->file = $file;
		$this->is_service = false;
	}
	
	public function __toString() {
		$this->inc($this->file);
		// __toString must return a String value
		return '';
	}

	public function inc($file) {
		include($this->private_file($file));
	}

	/**
	 * Get the request path to a public resource of this
	 * resource.
	 *
	 * Example:
	 * 	echo '<img src="'.TeeWee::$PAGE->public_url('picture.png').'" />';
	 *
	 * @return the absolute request path to the public resource
	 **/
	public function public_url($file) {
		return
			'/'.TeeWee::$CONFIG->TEEWEE_PUBLIC.'/'.
			$this->folder.'/'.$file;
	}

	/**
	 * Get the file path to a private resource of this
	 * resource.
	 * 
	 * Example:
	 * 	$sql_init = fopen(TeeWee::$PAGE->private_file('init.sql');
	 *
	 * @return the absolute file path to the private resource
	 **/
	public function private_file($file) {
		return $this->folder.'/'.$file;
	}

}
?>
